package com.dm.shop.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dm.shop.common.enums.ResultEnum;
import com.dm.shop.entity.User;
import com.dm.shop.service.UserService;
import com.dm.shop.utils.CommonUtil;
import com.dm.shop.utils.ResultUtil;
import com.dm.shop.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author MyBatisPlusGenerater-Saiya Wang
 * @since 2021-07-20
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/getUserByNickName/{nickname}")
    @ApiOperation("根据关键词搜索")
    public Result getUserByNickName(String nickname){
        return userService.getUserByNickName(nickname);

    }

    @GetMapping("/getUserInfo")
    @ApiOperation("获取当前用户")
    public Result getUserInfo(){
        return ResultUtil.success(CommonUtil.getCurrentUser());

    }

    @PutMapping("/editUser")
    @ApiOperation("修改用户信息")
    public Result editUser(@RequestBody User user){
        return userService.editUser(user);
    }

    @GetMapping("/getAllUserInfo/{page}/{size}")
    @ApiOperation("获取全部信息")
    public Result getAllUserInfo(@PathVariable("page") int page,@PathVariable("size") int size){
        return userService.getAllUserInfo(page, size);
    }

    @DeleteMapping("/del/{uid}")
    @ApiOperation("根据用户的id删除用户")
    public Result delUserById(@PathVariable("uid") int id)
    {
        return userService.delUser(id);

    }

    @PostMapping("/addUser")
    @ApiOperation("添加用户")
    public Result addUser(@RequestBody User user){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("nick_name",user.getNickName());
        if(userService.getOne(wrapper) != null)
        {
            return ResultUtil.error("昵称已经被占用");
        }
        wrapper = new QueryWrapper<>();
        wrapper.eq("phone_number",user.getPhoneNumber());
        if(userService.getOne(wrapper)!=null)
        {
            return ResultUtil.error("电话已经被注册");
        }
        wrapper = new QueryWrapper<>();
        wrapper.eq("email",user.getEmail());
        if(userService.getOne(wrapper) != null)
        {
            return ResultUtil.error("邮箱已被注册");
        }
        return userService.addUser(user);
    }

    @GetMapping("/getNew/{id}")
    @ApiOperation("根据用户id获取用户")
    public Result getById(@PathVariable("id") Integer id)
    {
        User user = userService.getById(id);
        if(user != null)
        {
            return ResultUtil.success(user);
        }
        return ResultUtil.error("用户不存在");
    }
}
